import { infoDesignInfo } from './init/index'
import { createDesignNodeEle } from './add/index'

import type { BwDesignNodeInfoModel } from './model'
import {
  BwCustomComSoltTypeEnum,
  type BwCustomComStructModel,
  type BwCustomComSlotInfoModel,
} from '@bitwit/base-com-render'

export * from './axios'
export type * from './axios/model'

export const designUtils = {
  /**
   * 初始化设计信息
   * @param info                      设计信息
   */
  infoDesignInfo,

  /** 生成节点元素 */
  createDesignNodeEle,

  /** 查询当前组件外放插槽信息 */
  findComSlotInfo(
    list: Array<BwCustomComSlotInfoModel>,
    info: BwCustomComSlotInfoModel
  ) {
    const resData: Record<string, any> = { index: null, info: null }
    if (Array.isArray(list) && list.length) {
      const type = info.slotType

      list.find((n, index) => {
        if (type === n.slotType) {
          switch (type) {
            case BwCustomComSoltTypeEnum.convention: {
              const slotCode = info.conventionSlotInfo?.slotCode
              const comSlotCode = n.conventionSlotInfo?.slotCode
              if (slotCode === comSlotCode) {
                resData.info = n
                resData.index = index
              }
              break
            }
            case BwCustomComSoltTypeEnum.trends: {
              const slotCode = info.trendsSlotInfo?.logicCode
              const comSlotCode = n.trendsSlotInfo?.logicCode
              if (slotCode === comSlotCode) {
                resData.info = n
                resData.index = index
              }
              break
            }
          }
        }
      })
    }

    return resData
  },

  /**
   * 查询节点信息
   * @param structs                   数据 DOM 列表
   * @param nodeId                    查询节点的ID
   */
  findDomNodeInfo(
    structs: Array<BwCustomComStructModel>,
    nodeId: string
  ): Nullable<BwDesignNodeInfoModel> {
    let findNodeInfo: Nullable<BwDesignNodeInfoModel> = null

    if (Array.isArray(structs) && structs.length) {
      structs.some((n, index, list) => {
        const { nodeId: curNodeId, children } = n
        if (curNodeId === nodeId) {
          findNodeInfo = { node: n, index, list, pNode: null }
        }
        // 遍历子节点
        else if (children) {
          Object.keys(children).some((k) => {
            const childNodes = children[k] ?? []
            findNodeInfo = this.findDomNodeInfo(childNodes, nodeId)
            if (findNodeInfo && !findNodeInfo.pNode) {
              findNodeInfo.pNode = n
            }

            return !!findNodeInfo
          })
        }
        return !!findNodeInfo
      })
    }

    return findNodeInfo
  },
}
